package com.zoweunion.mechanic.service.base.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zoweunion.mechanic.dao.app.ToolCarDataMapper;
import com.zoweunion.mechanic.dao.base.VehicleDataMapper;
import com.zoweunion.mechanic.entity.VehicleDataBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.service.app.impl.OrderServicelmpl;
import com.zoweunion.mechanic.service.app.impl.ToolCarDataServiceImpl;
import com.zoweunion.mechanic.service.base.VehicleDataService;
import com.zoweunion.mechanic.util.DateUtil;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.Orgin;
import com.zoweunion.mechanic.util.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

@Service
@Transactional
public class VehicleDataServiceImpl implements VehicleDataService {

    @Autowired
    private VehicleDataMapper vehicleDataMapper;
    @Autowired
    private ToolCarDataServiceImpl toolCarDataServiceImpl;
    @Autowired
    private ToolCarDataMapper toolCarDataMapper;
    @Autowired
    private OrderServicelmpl orderServicelmpl;

    @Override
    public Map<String, Object> vehicleTodayStatisticsData(Map<String, Object> reqmap) throws ParseException {
        String thingsId = Orgin.getString(reqmap, "things_id");
        Date sampleDate = Orgin.getDate(reqmap, "sample_date");
        Date t = new Date();
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = df1.format(t);
        Map<String, Object> datamap = new HashMap<>();
        //查询开工时间以及结束时间
        String workHoursJson = toolCarDataMapper.getWorkHoursByDate(thingsId, reqmap.get("sample_date").toString());
        if (workHoursJson != null) {
            Map<String, Object> workHoursObj =  JSON.parseObject(workHoursJson, Map.class);
            List<String> startTimeList = (List<String>) workHoursObj.get("startTimeList");
            List<String> endTimeList = (List<String>) workHoursObj.get("endTimeList");
            if(startTimeList.size() > 0){
                double start_work_time =  Double.valueOf(startTimeList.get(0));
                int hour = (int) (start_work_time % 24);
                int minutes = (int) (start_work_time % 1 * 60);
                String startWorkTime = (hour < 10 ? "0" + hour : hour) + ":" + (minutes < 10 ? "0" + minutes : minutes);
                double end_work_time =  Double.valueOf(startTimeList.get(endTimeList.size() - 1));
                int hour1 = (int) (end_work_time % 24);
                int minutes1 = (int) (end_work_time % 1 * 60);
                String endWorkTime = (hour1 < 10 ? "0" + hour1 : hour1) + ":" + (minutes1 < 10 ? "0" + minutes1 : minutes1);
                datamap.put("start_work_time", startWorkTime);
                datamap.put("end_work_time", endWorkTime);
            }else{
                datamap.put("start_work_time", "未开工");
            }
        }
        //历史数据
        if (!dateString.equals(Orgin.getString(reqmap, "sample_date"))) {
            //everyday表获取工时和油耗、燃油液位
            Map<String, Object> map = vehicleDataMapper.vehicleTodayStatisticsData(reqmap);
            if (map != null) {
                double fuelConsumption = (double) map.get("fuel_consumption");
                double workHours = Orgin.getDoubleValue(map, "work_hours");
                String fuelGauge = Orgin.getDoubleValue(map, "fuel_gauge") + "%";
                double fuelConsumptionAverage = 0;
                if (workHours != 0) {
                    fuelConsumptionAverage = fuelConsumption / workHours;
                }
                datamap.put("work_hours", String.format("%.1f", workHours));
                datamap.put("fuel_consumption", String.format("%.1f", fuelConsumption));
                datamap.put("fuel_consumption_average", String.format("%.1f", fuelConsumptionAverage));
                datamap.put("fuel_gauge", fuelGauge);
            } else {
                datamap.put("fuel_consumption", 0);
                datamap.put("work_hours", 0);
                datamap.put("fuel_consumption_average", 0);
                datamap.put("fuel_gauge", "0.0%");
            }
            Date sampleDateNew = new SimpleDateFormat("yyyy-MM-dd").parse("2020-06-13");
            List<Map<String, Object>> sampleTimeList = new ArrayList<>();
            if (sampleDate.compareTo(sampleDateNew) > 0) {
                String tableName = toolCarDataServiceImpl.selectTableByThingsIdByDate(thingsId, sampleDate);
                //获取查询日期的怠速时间(查询日期最后怠速总时长-查询日期最开始怠速总时长)
                Map<String, Object> map1 = new HashMap<>();
                map1.put("date", Orgin.getString(reqmap, "sample_date"));
                double idleTime = Orgin.getDoubleValue(this.getIdleTimeOneDay(thingsId, map1), "idleTime");
                datamap.put("idleTime", idleTime);
                //从tb1获取开关机时间和最后一条记录gps定位地址
                sampleTimeList = vehicleDataMapper.sampleTimeList(thingsId, tableName + "_tb1", Orgin.getString(reqmap, "sample_date"));
            }
            if (sampleTimeList.size() >= 2) {
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date endTime = df.parse(sampleTimeList.get(0).get("sample_time").toString());
                Date startTime = df.parse(sampleTimeList.get(sampleTimeList.size() - 1).get("sample_time").toString());
                String start_time = startTime.toString().substring(11,16);
                String end_time = endTime.toString().substring(11,16);
                datamap.put("end_time", end_time);
                datamap.put("start_time", start_time);
                datamap.put("status", 2);
                datamap.put("GPSlongitude", sampleTimeList.get(0).get("GPSlongitude").toString());
                datamap.put("GPSlatitude", sampleTimeList.get(0).get("GPSlatitude").toString());
            } else {
                datamap.put("start_time", "00:00");
                datamap.put("end_time", "00:00");
                datamap.put("status", 2);
                datamap.put("GPSlongitude", "");
                datamap.put("GPSlatitude", "");
            }
        } else {
            //当日数据
            Map<String, Object> map1 = new HashMap<>();
            Map<String, Object> hashMap = new HashMap<>();
            map1.put("date", Orgin.getString(reqmap, "sample_date"));
            map1.put("workHour", "");
            map1.put("fuel", "");
            //获取当日油耗和工时统计
            Map<String, Object> mapCount = toolCarDataMapper.carCountFuelWork(Orgin.getString(reqmap, "sample_date"), thingsId);
            if (mapCount != null) {
                double workHours = Orgin.getDouble(this.getWorkHour(thingsId, map1), "workHour");
                double fuelConsumption = Orgin.getDouble(this.getFuelConsumption(thingsId, map1, hashMap), "fuel");
                String fuelGauge = Orgin.getDoubleValue(this.getFuelGaugeData(thingsId,map1), "fuel_gauge") + "%";
                double idleTime = Orgin.getDoubleValue(this.getIdleTimeOneDay(thingsId, map1), "idleTime");
                double fuelConsumptionAverage = 0;
                if (workHours != 0) {
                    fuelConsumptionAverage = fuelConsumption / workHours;
                }
                datamap.put("fuel_consumption",  String.format("%.1f", fuelConsumption));
                datamap.put("work_hours", String.format("%.1f", workHours));
                datamap.put("fuel_consumption_average",  String.format("%.1f", fuelConsumptionAverage));
                datamap.put("fuel_gauge", fuelGauge );
                datamap.put("idleTime", idleTime);
            } else {
                datamap.put("fuel_consumption", 0);
                datamap.put("work_hours", 0);
                datamap.put("fuel_consumption_average", 0);
                datamap.put("fuel_gauge", "0.0%");
                datamap.put("idleTime", 0);
            }
            //通过data_real表获取开关机时间和定位，关机时间根据status显示而考虑是否显示
            Map<String, Object> realDataMap = toolCarDataMapper.selectDataByThingsId(thingsId);
            if (realDataMap != null) {
                // 显示卫星数据页面
                if (realDataMap.get("GP_NUM") != null) {
                    if (realDataMap.get("GP_NUM").toString().equals("1")) {
                        datamap.put("GPSsatellite",true);
                    }else {
                        datamap.put("GPSsatellite",false);
                    }
                }else {
                    datamap.put("GPSsatellite",false);
                }
                datamap.put(Constants.THINGS_GPSlongitude,realDataMap.get(Constants.THINGS_GPSlongitude));
                datamap.put(Constants.THINGS_GPSlatitude,realDataMap.get(Constants.THINGS_GPSlatitude));
                if (realDataMap.get("close_time") == null) {
                    datamap.put("end_time", "00:00");
                }else {
                    LocalDateTime close_time = DateUtil.formatTimestampToTime((Timestamp) realDataMap.get("close_time"));
                    datamap.put("end_time", DateUtil.formatTime(close_time).substring(11, 16));
                }
                if (realDataMap.get("start_time") == null) {
                    datamap.put("start_time", "00:00");
                }else {
                    LocalDateTime start_time = DateUtil.formatTimestampToTime((Timestamp) realDataMap.get("start_time"));
                    datamap.put("start_time", DateUtil.formatTime(start_time).substring(11, 16));
                }
            }else {
                datamap.put("end_time", "00:00");
                datamap.put("start_time", "00:00");
            }
            if (Orgin.getString(realDataMap, "status") != null) {
                datamap.put("status", realDataMap.get("status") );
            }else {
                datamap.put("status", 1);
            }
        }
        return datamap;
    }

    public Map<String, Object> vehicleStatisticsData(Map<String, Object> reqmap) throws ParseException {
        String thingsId = Orgin.getString(reqmap, "things_id");
        Date sampleDate = Orgin.getDate(reqmap, "sample_date");
        Date t = new Date();
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = df1.format(t);
        Map<String, Object> datamap = new HashMap<>();
        //历史数据
        if (!dateString.equals(Orgin.getString(reqmap, "sample_date"))) {
            //everyday表获取工时和油耗
            Map<String, Object> map = vehicleDataMapper.vehicleTodayStatisticsData(reqmap);
            if (map != null) {
                double fuelConsumption = (double) map.get("fuel_consumption");
                double workHours = Orgin.getDoubleValue(map, "work_hours");
                double fuelConsumptionAverage = 0;
                if (workHours != 0) {
                    fuelConsumptionAverage = fuelConsumption / workHours;
                }
                datamap.put("work_hours", String.format("%.1f", workHours));
                datamap.put("fuel_consumption", String.format("%.1f", fuelConsumption));
                datamap.put("fuel_consumption_average", String.format("%.1f", fuelConsumptionAverage));
            } else {
                datamap.put("fuel_consumption", 0);
                datamap.put("work_hours", 0);
                datamap.put("fuel_consumption_average", 0);
            }
        } else {
            //当日数据
            Map<String, Object> map1 = new HashMap<>();
            Map<String, Object> hashMap = new HashMap<>();
            map1.put("date", Orgin.getString(reqmap, "sample_date"));
            map1.put("workHour", "");
            map1.put("fuel", "");
            //获取当日油耗和工时统计
            Map<String, Object> mapCount = toolCarDataMapper.carCountFuelWork(Orgin.getString(reqmap, "sample_date"), thingsId);
            if (mapCount != null) {
                double workHours = Orgin.getDouble(this.getWorkHour(thingsId, map1), "workHour");
                double fuelConsumption = Orgin.getDouble(this.getFuelConsumption(thingsId, map1, hashMap), "fuel");
                double fuelConsumptionAverage = 0;
                if (workHours != 0) {
                    fuelConsumptionAverage = fuelConsumption / workHours;
                }
                datamap.put("fuel_consumption", String.format("%.1f", fuelConsumption));
                datamap.put("work_hours", String.format("%.1f", workHours));
                datamap.put("fuel_consumption_average", String.format("%.1f", fuelConsumptionAverage));
            } else {
                datamap.put("fuel_consumption", 0);
                datamap.put("work_hours", 0);
                datamap.put("fuel_consumption_average", 0);
            }
        }
        return datamap;
    }


    public Map<String, Object> vehicleStatisticsDataNew(Map<String, Object> reqmap) throws ParseException {
        String thingsId = Orgin.getString(reqmap, "things_id");
        Date t = new Date();
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = df1.format(t);
        Map<String, Object> datamap = new HashMap<>();
        datamap.put("fuel_consumption_average", 0);
        //历史数据
//        if (!dateString.equals(Orgin.getString(reqmap, "sample_date"))) {
//            //everyday表获取工时和油耗
//            Map<String, Object> map = vehicleDataMapper.vehicleTodayStatisticsDataNew(reqmap);
//            if (map != null) {
//                double fuel_consumption_average = (double) map.get("fuel_consumption_average");
//                datamap.put("fuel_consumption_average", String.format("%.1f", fuel_consumption_average));
//            }
//        } else {
//            //当日数据
//            Map<String, Object> map1 = new HashMap<>();
//            Map<String, Object> hashMap = new HashMap<>();
//            map1.put("date", Orgin.getString(reqmap, "sample_date"));
//            map1.put("workHour", "");
//            map1.put("fuel", "");
//            //获取当日油耗和工时统计
//            double workHours = Orgin.getDouble(this.getWorkHour(thingsId, map1), "workHour");
//            double fuelConsumption = Orgin.getDouble(this.getFuelConsumption(thingsId, map1, hashMap), "fuel");
//            double fuelConsumptionAverage = 0;
//            fuelConsumptionAverage = fuelConsumption / workHours;
//            datamap.put("fuel_consumption_average", String.format("%.1f", fuelConsumptionAverage));
//        }
        return datamap;
    }

    @Override
    public Map<String, Object> vehicleTodayDataDetail(Map<String, Object> reqmap) throws ParseException {
        Map<String, Object> dataDateMap = new HashMap<>();
        List<String> sampleTimeList = new ArrayList<>();
        List<Double> value = new ArrayList<>();
        String thingsId = Orgin.getString(reqmap, "things_id");
        Date sampleDate = Orgin.getDate(reqmap, "sample_date");
        Date sampleDateNew = new SimpleDateFormat("yyyy-MM-dd").parse("2020-06-13");
        if (sampleDate.compareTo(sampleDateNew) > 0) {
            String tableName = toolCarDataServiceImpl.selectTableByThingsIdByDate(thingsId, sampleDate);
            Map<String, Object> map = new HashMap<>();
            map.put("things_id", thingsId);
            map.put("tb1", tableName + "_tb1");
            map.put("key", Orgin.getString(reqmap, "type"));
            map.put("sample_date", Orgin.getString(reqmap, "sample_date"));
            List<Map<String, Object>> dataDetailList = new ArrayList<>();
            dataDetailList = vehicleDataMapper.vehicleTodayDataDetail(map);
            dataDetailList.forEach(item -> {
                if (!sampleTimeList.contains(Orgin.getString(item, "sample_time"))) {
                    sampleTimeList.add(Orgin.getString(item, "sample_time"));
                    value.add(Orgin.getDouble(item, Orgin.getString(reqmap, "type")));
                }
            });
            dataDateMap.put("sample_time", sampleTimeList);
            dataDateMap.put("type", value);
        } else {
            dataDateMap.put("sample_time", sampleTimeList);
            dataDateMap.put("type", value);
        }
            return dataDateMap;
    }

    @Override
    public List<Map<String, Object>> vehicleData(Map<String, Object> reqmap) throws MyException{
        Date startTime = Orgin.getDate(reqmap, "startTime");
        Date endTime = Orgin.getDate(reqmap, "endTime");
        String thingsId = Orgin.getString(reqmap, "things_id");
        int currentPage = Orgin.getIntValue(reqmap, "currentPage");
        int pageSize = Orgin.getIntValue(reqmap, "pageSize");
        List<String> ymd = OrderServicelmpl.createYMD(startTime, endTime);
        if (ymd.size()>31) {
            throw new MyException(Constants.CODE_SUCCESS, "所选日期超过最大可选日期");
        } else {
            //此处开启分页
            Collections.reverse(ymd);
            List<String> collect =
                    ymd.stream().skip((long) (currentPage - 1) *pageSize).limit(pageSize)
                            .collect(toList());
            List<Map<String, Object>> dataList = new ArrayList<>();
            collect.forEach(item -> {
                Map<String, Object> map = new HashMap<>();
                map.put("things_id", thingsId);
                map.put("sample_date", item);
                try {
                    Map<String, Object> dataMap = this.vehicleStatisticsData(map);
                    if (Orgin.getDouble(dataMap, "work_hours") >= 24 || Orgin.getDouble(dataMap, "work_hours") <= 0) {
                        map.put("work_hours", "0小时0分钟");
                        map.put("fuel_consumption", 0);
                        map.put("fuel_consumption_average", 0);
                    } else {
                        map.put("work_hours", ((int) Orgin.getDoubleValue(dataMap, "work_hours") * 60) / 60 + "小时" +
                                ((int) (Orgin.getDoubleValue(dataMap, "work_hours") * 60) % 60) + "分钟");
                        map.put("fuel_consumption", (String.format("%.1f", Orgin.getDouble(dataMap, "fuel_consumption"))));
                        map.put("fuel_consumption_average", (String.format("%.1f", Orgin.getDouble(dataMap, "fuel_consumption_average"))));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                dataList.add(map);
            });
            return dataList;
        }
    }

    @Override
    public List<VehicleDataBean> exportVehicleData(Map<String, Object> reqmap) {
        Date startTime = Orgin.getDate(reqmap, "startTime");
        Date endTime = Orgin.getDate(reqmap, "endTime");
        String thingsId = Orgin.getString(reqmap, "things_id");
        List<String> ymd = this.createYMD(startTime, endTime);
        List<VehicleDataBean> dataListExport = new ArrayList<>();
        ymd.forEach(item->{
            Map<String, Object> map = new HashMap<>();
            map.put("things_id", thingsId);
            map.put("sample_date", item);
            try {
                Map<String, Object> dataMap = this.vehicleTodayStatisticsData(map);
                dataListExport.add(VehicleDataBean.builder()
                        .sampleData(item)
                        .workHours(String.format("%.1f", Orgin.getDouble(dataMap, "work_hours")))
                        .fuelConsumption(String.format("%.1f", Orgin.getDouble(dataMap, "fuel_consumption")))
                        .fuelConsumptionAverage(String.format("%.1f", Orgin.getDouble(dataMap, "fuel_consumption_average")))
                        .build());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
        Collections.sort(dataListExport, new Comparator<VehicleDataBean>(){

            public int compare(VehicleDataBean o1, VehicleDataBean o2) {
                String name1 = o1.getSampleData();//name1是从你list里面拿出来的一个
                String name2 = o2.getSampleData(); //name1是从你list里面拿出来的第二个name
                return name2.compareTo(name1);
            }
        });
        return dataListExport;
    }

    @Override
    public List<Map<String, Object>> vehicleDataMonth(Map<String, Object> reqmap) throws MyException, ParseException {
        if (Orgin.getString(reqmap, "type").equals("month")) {
            DateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date startTime = sdf.parse(Orgin.getString(reqmap, "startTime"));
            Date endTime = sdf.parse(Orgin.getString(reqmap, "endTime"));
            List<String> ym = this.createYM(startTime, endTime);
            if (ym.size()>12) {
                throw new MyException(Constants.CODE_SUCCESS, "所选日期超过最大可选日期");
            } else {
                List<Map<String, Object>> dataMonthList = new ArrayList<>();
                ym.forEach(item -> {
                    Map<String, Object> map = new HashMap<>();
                    List<Map<String, Object>> dataList = vehicleDataMapper.vehicleDataMonth(reqmap);
                    double work_hours = dataList.stream().filter(
                            item2 -> item.equals(Orgin.getString(item2, "sample_date"))).mapToDouble(item2 -> Orgin.getDouble(item2, "work_hours")).sum();
                    double fuel_consumption = dataList.stream().filter(item2 -> item.equals(Orgin.getString(item2, "sample_date"))).mapToDouble(item2 -> Orgin.getDouble(item2, "fuel_consumption")).sum();
                    map.put("sample_time", item);
                    map.put("work_hours", String.format("%.1f", work_hours));
                    map.put("fuel_consumption", String.format("%.1f", fuel_consumption));
                    dataMonthList.add(map);
                });
                return dataMonthList;
            }
        } else {
            Date startTime = Orgin.getDate(reqmap, "startTime");
            Date endTime = Orgin.getDate(reqmap, "endTime");
            String thingsId = Orgin.getString(reqmap, "things_id");
            List<String> ymd = this.createYMD(startTime, endTime);
            if (ymd.size()>31) {
                throw new MyException(Constants.CODE_SUCCESS, "所选日期超过最大可选日期");
            } else {
                List<Map<String, Object>> arrayList = new ArrayList<>();
                Map<String, Object> hashMap = new LinkedHashMap<>();
                ymd.forEach(item -> {
                    Map<String, Object> map1 = new HashMap<>();
//                    map1.put("sample_time", item.substring(5, 10));
                    map1.put("date", item);
                    map1.put("work_hours", "");
                    map1.put("fuel_consumption", "");
                    map1.put("sample_time", item.substring(5,10));
                    Map<String, Object> mapCount = toolCarDataMapper.carCountFuelWork(item, thingsId);
                    if (mapCount != null) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String nowDate = simpleDateFormat.format(new Date());
                        if (item.equals(nowDate)) {
                            //如果是当天 获取当日工时
                            map1 = this.getWorkHour(thingsId, map1);
                            //获取当日消耗燃油
                            map1 = this.getFuelConsumption(thingsId, map1, hashMap);
                            map1.put("work_hours", (String.format("%.1f", Orgin.getDouble(map1, "workHour"))));
                            map1.put("fuel_consumption", (String.format("%.1f", Orgin.getDouble(map1, "fuel"))));
                        } else {
                            if (Double.valueOf(Orgin.getString(mapCount, "work_hours")) < 24) {
                                map1.put("work_hours", (String.format("%.1f", Orgin.getDouble(mapCount, "work_hours"))));
                            } else {
                                map1.put("work_hours", "24.0");
                            }
                            map1.put("fuel_consumption", (String.format("%.1f", Orgin.getDouble(mapCount, "fuel_consumption"))));
                        }
                    } else {
                        map1.put("work_hours", "0.0");
                        map1.put("fuel_consumption", "0.0");
                    }
                    arrayList.add(map1);
                });
                return arrayList;
            }
        }
    }

    @Override
    public Map<String, Object> vehicleOilAverage(Map<String, Object> reqmap)  throws MyException{
        Map<String, Object> vehicleOilAverage = new HashMap<>();
        List<String> sampleTimes = new ArrayList<>();
        List<String> oilAverage = new ArrayList<>();
        Date startTime = Orgin.getDate(reqmap, "startTime");
        Date endTime = Orgin.getDate(reqmap, "endTime");
        String thingsId = Orgin.getString(reqmap, "things_id");
        List<String> ymd = this.createYMD(startTime, endTime);
        if (ymd.size()>31) {
            throw new MyException(Constants.CODE_SUCCESS, "所选日期超过最大可选日期");
        } else {
            //everyday表获取工时和油耗
            List<Map<String, Object>> mapList = vehicleDataMapper.vehicleTodayStatisticsDataNew(reqmap);
            List<String> sampleDate = mapList.stream().map(i -> Orgin.getString(i, "sample_date"))
                    .collect(toList());
            ymd.forEach(item -> {
                sampleTimes.add(item.substring(5,10));
            });
            List<String> collect = ymd.stream().filter(item -> !sampleDate.contains(item)).collect(toList());
            collect.forEach(item->{
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("sample_date",item);
                hashMap.put("fuel_consumption_average",0.0);
                mapList.add(hashMap);
            });
            List<Map<String, Object>> sample_date = mapList.stream()
                    .sorted(Comparator.comparing(i -> i.get("sample_date").toString()))
                    .collect(toList());
            oilAverage = sample_date.stream().map(i -> Orgin.getString(i, "fuel_consumption_average"))
                    .collect(toList());
            Date t = new Date();
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = df1.format(t);
            if (dateString.equals(Orgin.getString(reqmap, "endTime"))) {
                //当日数据
               Map<String, Object> map1 = new HashMap<>();
               Map<String, Object> hashMap = new HashMap<>();
               map1.put("date",  df1.format(endTime));
               map1.put("workHour", 0.0);
               map1.put("fuel", 0.0);
               //获取当日油耗和工时统计
               double workHours = Orgin.getDouble(this.getWorkHour(thingsId, map1), "workHour");
               double fuelConsumption = Orgin.getDouble(this.getFuelConsumption(thingsId, map1, hashMap), "fuel");
               double fuelConsumptionAverage = 0;
               fuelConsumptionAverage = fuelConsumption / workHours;
               oilAverage.remove(oilAverage.size()-1);
               if (workHours!=0){
                   oilAverage.add(String.format("%.1f", fuelConsumptionAverage));
               }else {
                   oilAverage.add("0.0");
               }
            }
            vehicleOilAverage.put("sampleTimes", sampleTimes);
            vehicleOilAverage.put("oilAverage", oilAverage);
            return vehicleOilAverage;
        }
    }

    public static List<String> createYM(Date startDate, Date endDate) {
        List<String> ls = new ArrayList<String>();
        int months = differentMonths(startDate, endDate);
        String ym = "";
        for (int i = 0; i <= months; i++) {

            Calendar cal = Calendar.getInstance();
            cal.setTime(startDate);
            cal.add(Calendar.MONTH, i);
            Date time = cal.getTime();
            SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM");
            String localTime = localFormater.format(time);
            ls.add(localTime);
        }
        return ls;
    }

    public static int differentMonths(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int month1 = cal1.get(Calendar.MONTH);
        int month2 = cal2.get(Calendar.MONTH);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2)   //不同年
        {
            return 12 + (month2 - month1);
        } else    //同一年
        {
            return month2 - month1;
        }
    }

    public Map<String,Object> getWorkHour(String thingsId,Map<String,Object> resultMap){
//        String tableName = this.selectTableByThingsId(thingsId);
        String tableName = this.selectTableByThingsIdByDate(thingsId, Orgin.getDate(resultMap, "date"));
        //查询数据
        Map<String, Object> carDataMapOperatingHour = toolCarDataMapper.carDataMapOperatingHour(thingsId, tableName + "_tb1", tableName + "_tb2");
        if (carDataMapOperatingHour != null && carDataMapOperatingHour.get("maxEngineTotalHours") != null && carDataMapOperatingHour.get("minEngineTotalHours") != null) {
            String maxEngineTotalHours = carDataMapOperatingHour.get("maxEngineTotalHours").toString();
            String minEngineTotalHours = carDataMapOperatingHour.get("minEngineTotalHours").toString();
            // 如果发动机总时长大于10万说明没有读取到发动机总工时的数据
            if (Double.parseDouble(maxEngineTotalHours) > 0 && Double.parseDouble(maxEngineTotalHours) < 100000) {
                resultMap.put(Constants.WORK_HOUR, (String.format("%.1f", Double.parseDouble(maxEngineTotalHours)-Double.parseDouble(minEngineTotalHours))) );
            }else {
                resultMap.put(Constants.WORK_HOUR, "0");
            }
        } else {
            resultMap.put(Constants.WORK_HOUR, "0");
        }
        return  resultMap;
    }

    //通过thingsid获取表名
    public  String selectTableByThingsIdByDate(String thingsId,Date date){
        Map<String, Object> map1 = toolCarDataMapper.selectByThingsId(thingsId);

        String tableName = "pc_car_";
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);

        String bsd = "";
        tableName = tableName + "other_" + year + "_W" + weekOfYear;

        if (map1 != null) {

            if (map1.containsKey("s_id")) {

                if (map1.get("s_id") != null) {

                    bsd = map1.get("bsd").toString();

                    tableName = "pc_car_";
                    tableName = tableName + bsd.substring(bsd.length() - 6, bsd.length())
                            + "_" + year + "_W" + weekOfYear;
                }
            }
        }

        return tableName;
    }

    public Map<String, Object> getFuelConsumption(String thingsId, Map<String, Object> map1,Map<String, Object> map2) {
        String tableName = this.selectTableByThingsIdByDate(thingsId, Orgin.getDate(map1, "date"));
        //查询数据
        double fuelConsumption = toolCarDataMapper.getFuelConsumption(thingsId, tableName + "_tb1");
        //注释无用代码
//        if (fuelConsumption==0){
//            //查询计算油耗
//            fuelConsumption=toolCarDataMapper.selectEveryDayFuel(thingsId);
//        }
        map1.put("fuel", (String.format("%.1f", fuelConsumption)));
        return map1;
    }

    public Map<String, Object> getFuelGaugeData(String thingsId, Map<String, Object> map1){
        String tableName = this.selectTableByThingsIdByDate(thingsId, Orgin.getDate(map1, "date"));
        //查询数据
        double fuelGauge = toolCarDataMapper.getFuelGaugeData(thingsId, tableName + "_tb1");
        map1.put("fuelGauge", (String.format("%.1f", fuelGauge)));
        return map1;
    }

    private Map<String, Object> getIdleTimeOneDay(String thingsId, Map<String, Object> map1) {
        String tableName = this.selectTableByThingsIdByDate(thingsId, Orgin.getDate(map1, "date"));
        //查询数据
        double idleTime = toolCarDataMapper.getIdleTimeOneDay(thingsId, tableName + "_tb1", map1.get("date").toString());
        map1.put("idleTime", (String.format("%.1f", idleTime)));
        return map1;
    }

    public static List<String> createYMD(Date startDate, Date endDate) {
        List<String> ls = new ArrayList<String>();
        int days = differentDays(startDate, endDate);
        String ymd = "";
        for (int i = 0; i <= days; i++) {

            Calendar cal = Calendar.getInstance();
            cal.setTime(startDate);
            cal.add(Calendar.DATE, i);
            Date time = cal.getTime();
            SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd");
            String localTime = localFormater.format(time);
            ls.add(localTime);
        }
        return ls;
    }

    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2)   //同一年
        {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
                {
                    timeDistance += 366;
                } else    //不是闰年
                {
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else    //不同年
        {
            return day2 - day1;
        }
    }
}
